﻿using System;
using System.Windows.Forms;

namespace PhiStore.Storage.UI
{
    internal partial class StorageUI : Form
    {
        public StorageUI()
        {
            InitializeComponent();
            this.Text = "Add Storage Device";
        }

        internal IStorageDevice Device
        {
            get 
            {
                if (LocalRadio.Checked)
                {
                    return new LocalStorage(Basepath.Text, 1024 * 1024 * (long)SizeField.Value);
                }
                else if (FTPRadio.Checked)
                {
                    return new FtpStorage(Basepath.Text, Username.Text, Password.Text, 1024 * 1024 * (long)SizeField.Value);
                }
                else
                {
                    throw new NotImplementedException("Only Local and FTP are implemented");
                }
            }
            set 
            {
                this.Text = "Edit Storage Device";

                Basepath.Text = value.BasePath;
                SizeField.Value = value.ReservedBytes / 1024 / 1024;

                if (value is LocalStorage)
                {
                    LocalStorage val = (LocalStorage)value;
                    LocalRadio.Checked = true;
                    
                }
                else if (value is FtpStorage)
                {
                    FtpStorage val = (FtpStorage)value;
                    FTPRadio.Checked = true;
                    Username.Text = val.UserName;
                }
                else
                {
                    throw new NotImplementedException("Only Local and FTP are implemented");
                }
            }
        }

        private void OKButton_Click(object sender, EventArgs e)
        {
            if (Device.Works())
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("These settings doesn't work...", "Error");
            }
        }

        private void Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Radio_CheckedChanged(object sender, EventArgs e)
        {
            if (LocalRadio.Checked)
            {
                Username.Enabled = false;
                Password.Enabled = false;
            }
            else
            {
                Username.Enabled = true;
                Password.Enabled = true;
            }
        }
    }
}
